package com.b2b.controller;


import com.alibaba.fastjson.JSONObject;
import com.b2b.model.MasterOrderDto;
import com.b2b.model.MasterOrderGoodsDto;
import com.b2b.model.OrdersListDto;
import com.b2b.model.StockDto;
import com.b2b.model.common.CategoryHot;
import com.b2b.model.common.ResponseBean;
import com.b2b.model.entity.*;
import com.b2b.model.entity.company.CompanyInfo;
import com.b2b.model.entity.goods.Category;
import com.b2b.model.entity.goods.Goods;
import com.b2b.model.entity.goods.Stock;
import com.b2b.service.*;
import com.b2b.service.goodsService.GoodsService;
import com.b2b.service.goodsService.StockService;
import com.b2b.util.CategoryUtil;
import com.b2b.util.CompanyInfoUtil;
import com.b2b.util.MasterOrderUtil;
import com.b2b.util.OrdersUtil;
import com.b2b.util.common.StatisticUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Column;
import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/masterOrder")
@CrossOrigin
@PropertySource("classpath:config.properties")
public class MasterOrderController {


    @Autowired
    MasterOrderService masterOrderService;

    @Autowired
    MasterOrderOrdersService masterOrderOrdersService;

    @Autowired
    CompanyInfoService companyInfoService;

    @Autowired
    MasterOrderGoodsService masterOrderGoodsService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    StockService stockService;

    @Autowired
    OrdersService ordersService;
    
    @Autowired
    OrdersGoodsService ordersGoodsService;

    @Autowired
    ShopService shopService;

    @Autowired
    OrdersUtil ordersUtil;



    @Autowired
    StatisticUtil statisticUtil;

    private final MasterOrderUtil masterOrderUtil;

    private final CompanyInfoUtil companyInfoUtil;
    @Autowired
    public MasterOrderController(MasterOrderUtil masterOrderUtil,CompanyInfoUtil companyInfoUtil){
        this.masterOrderUtil = masterOrderUtil;
        this.companyInfoUtil = companyInfoUtil;
    }

    @PostMapping("/add")
    public ResponseBean add(@RequestBody MasterOrderDto masterOrderDto){
        MasterOrder masterOrder = new MasterOrder();
        masterOrder.setMasterOrderId(masterOrderDto.getMasterOrderId());
        masterOrder.setTransactionValidity(masterOrderDto.getTransactionValidity());
        masterOrder.setRemarks(masterOrderDto.getRemarks());
        masterOrder.setExchangeAgreement(masterOrderDto.getExchangeAgreement());
        masterOrder.setExchangeRate(masterOrderDto.getExchangeRate());
        masterOrder.setDeliveryAgreement(masterOrderDto.getDeliveryAgreement());
        masterOrder.setOrderState('0');
        masterOrder.setSellerId(masterOrderDto.getSellerId());
        masterOrder.setBuyerId(companyInfoUtil.getCompanyIdByName(masterOrderDto.getBuyerName()));
        masterOrder.setBuyerState('0');
        masterOrder.setSellerState('0');
        masterOrder.setMasterOrderTime(new Date());
        masterOrder.setContractFilePath(masterOrderDto.getContractFilePath());
        masterOrderService.insert(masterOrder);

        Integer masterOrderId = masterOrder.getMasterOrderId();

        List<MasterOrderGoodsDto> stockList = masterOrderDto.getStockList();
        for (MasterOrderGoodsDto masterOrderGoodsDto:stockList
             ) {
            MasterOrderGoods masterOrderGoods = masterOrderUtil.getMasterOrderGoods(masterOrderGoodsDto);
            masterOrderGoods.setMasterOrderId(masterOrderId);
            masterOrderGoods.setCompletedNumber(0);
            masterOrderGoodsService.insert(masterOrderGoods);
        }

        StatisticUtil.updateNumOfOrders(masterOrderDto.getSellerId());

        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", null);
    }

    @PostMapping("/childAdd")
    public ResponseBean childAdd(@RequestBody MasterOrderDto masterOrderDto){
        MasterOrder masterOrder = masterOrderService.selectByPrimaryKey(masterOrderDto.getMasterOrderId());

        Orders orders = new Orders();
        orders.setOrderTime(new Timestamp(System.currentTimeMillis()));
        orders.setOrderType(masterOrderDto.getOrderType());
        orders.setTransportMode(masterOrderDto.getTransportMode());
        orders.setBuyerId(masterOrderDto.getBuyerId());
        orders.setSellerId(masterOrderDto.getSellerId());
        orders.setGoodsTotalPrice(masterOrderDto.getGoodsTotalPrice());
        orders.setFreight(masterOrderDto.getFreight());
        if (masterOrderDto.getGoodsTotalPrice()!=null&&masterOrderDto.getFreight()!=null){
            orders.setDues(masterOrderDto.getGoodsTotalPrice() + masterOrderDto.getFreight());
        }

        ordersService.insert(orders);

        Integer orderId =orders.getOrderId();

                MasterOrderOrders masterOrderOrders = new MasterOrderOrders();
        masterOrderOrders.setMasterOrderId(masterOrderDto.getMasterOrderId());
        masterOrderOrders.setOrderId(orderId);

        masterOrderOrdersService.insert(masterOrderOrders);

        List<MasterOrderGoodsDto> masterOrderGoodsDtoList = masterOrderDto.getStockList();

        for (MasterOrderGoodsDto m:masterOrderGoodsDtoList
             ) {
            OrdersGoods ordersGoods = new OrdersGoods();
            ordersGoods.setOrderId(orderId);
            ordersGoods.setStockId(m.getStockId());
            ordersGoods.setNumber(m.getNumber());
            ordersGoods.setPrice(m.getPrice());

            Stock stock = stockService.selectByPrimaryKey(ordersGoods.getStockId());
            stock.setNumber(stock.getNumber() - ordersGoods.getNumber());
            stockService.updateByPrimaryKeySelective(stock);
            ordersGoodsService.insert(ordersGoods);
        }

        StatisticUtil.updateNumOfOrders(masterOrderDto.getSellerId());

        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", null);
    }

    @DeleteMapping("/delete")
    public ResponseBean delete(@RequestParam Integer masterOrderId){
        if(masterOrderService.selectByPrimaryKey(masterOrderId).getBuyerState().equals('0')) {
            masterOrderService.deleteByPrimaryKey(masterOrderId);
            return new ResponseBean(HttpStatus.OK.value(), "删除成功", null);
        }else {
            return new ResponseBean(HttpStatus.OK.value(), "已签约成功，无权删除", null);
        }
    }

    @DeleteMapping("/cancel")
    public ResponseBean cancel(@RequestParam Integer masterOrderId){
        if(masterOrderService.selectByPrimaryKey(masterOrderId).getBuyerState().equals('0')) {
            masterOrderService.deleteByPrimaryKey(masterOrderId);
            MasterOrderGoods masterOrderGoods = new MasterOrderGoods();
            masterOrderGoods.setMasterOrderId(masterOrderId);

            List<MasterOrderGoods> masterOrderGoodsList = masterOrderGoodsService.select(masterOrderGoods);
            for (MasterOrderGoods m : masterOrderGoodsList
            ) {
                Stock stock = stockService.selectByPrimaryKey(m.getStockId());
                stock.setNumber(stock.getNumber() + m.getNumber());
            }
            return new ResponseBean(HttpStatus.OK.value(), "取消成功", null);
        }else {
            return new ResponseBean(HttpStatus.OK.value(), "已签约成功，无权删除", null);
        }
    }

    @DeleteMapping("/childDelete")
    public ResponseBean childDelete(@RequestParam Integer orderId){
        masterOrderOrdersService.deleteByPrimaryKey(orderId);
        ordersService.deleteByPrimaryKey(orderId);
        return new ResponseBean(HttpStatus.OK.value(), "删除成功", null);
    }

    @DeleteMapping("/childCancel")
    public ResponseBean childCancel(@RequestParam Integer orderId){
        masterOrderOrdersService.deleteByPrimaryKey(orderId);
        ordersService.deleteByPrimaryKey(orderId);
        OrdersGoods ordersGoods = new OrdersGoods();
        ordersGoods.setOrderId(orderId);

        List<OrdersGoods> ordersGoodsList = ordersGoodsService.select(ordersGoods);
        for (OrdersGoods o : ordersGoodsList
        ) {
            Stock stock = stockService.selectByPrimaryKey(o.getStockId());
            stock.setNumber(stock.getNumber() + o.getNumber());
            stockService.updateByPrimaryKeySelective(stock);
        }
        return new ResponseBean(HttpStatus.OK.value(), "取消成功", null);
    }

    @PutMapping("/updateInfo")
    public ResponseBean info(@RequestBody MasterOrderDto masterOrderDto){
        if(masterOrderDto.getMasterOrderId() != null) {
            MasterOrder masterOrder = new MasterOrder();
            masterOrderService.updateByPrimaryKeySelective(masterOrderUtil.getMasterOrder(masterOrderDto));
            List<MasterOrderGoodsDto> masterOrderGoodsDtoList = masterOrderDto.getStockList();
            for (MasterOrderGoodsDto m : masterOrderGoodsDtoList
            ) {
                masterOrderGoodsService.updateByPrimaryKeySelective(masterOrderUtil.getMasterOrderGoods(m));
            }
        }else {
            return new ResponseBean(HttpStatus.OK.value(), "协约不存在", null);
        }
        return new ResponseBean(HttpStatus.OK.value(), "修改成功", null);
    }

    @PutMapping("/accept")
    public ResponseBean accept(@RequestBody MasterOrderDto masterOrderDto){
        if(masterOrderDto.getMasterOrderId() != null) {
            MasterOrder masterOrder = masterOrderUtil.getMasterOrder(masterOrderDto);
            if(masterOrderService.selectCount(masterOrder) != 0) {
                masterOrder.setOrderState('2');
                masterOrderService.updateByPrimaryKeySelective(masterOrder);
            }else {
                return new ResponseBean(HttpStatus.OK.value(), "协约不存在", null);
            }
        }else {
            return new ResponseBean(HttpStatus.OK.value(), "内容为空", null);
        }
        return new ResponseBean(HttpStatus.OK.value(), "修改成功", null);
    }

    @PutMapping("/childComplete")
    public ResponseBean childComplete(@RequestParam Integer orderId){
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setOrderState('7');
        ordersService.updateByPrimaryKeySelective(orders);
        OrdersGoods ordersGoods = new OrdersGoods();
        orders.setOrderId(orderId);
        List<OrdersGoods> ordersGoodsList = ordersGoodsService.select(ordersGoods);
        MasterOrderOrders masterOrderOrders = new MasterOrderOrders();
        masterOrderOrders.setOrderId(orderId);
        masterOrderOrders = masterOrderOrdersService.selectOne(masterOrderOrders);
        List<CategoryHot> categoryHotList = new ArrayList<>();
        CategoryHot categoryHot = new CategoryHot();
        for (OrdersGoods o:ordersGoodsList
             ) {
            MasterOrderGoods masterOrderGoods = new MasterOrderGoods();
            masterOrderGoods.setMasterOrderId(masterOrderOrders.getMasterOrderId());
            masterOrderGoods.setStockId(o.getStockId());
            masterOrderGoods = masterOrderGoodsService.selectOne(masterOrderGoods);
            masterOrderGoods.setCompletedNumber(masterOrderGoods.getCompletedNumber() + o.getNumber());
            masterOrderGoodsService.updateByPrimaryKeySelective(masterOrderGoods);

            Stock stock = stockService.selectByPrimaryKey(o.getStockId());
            Goods goods = goodsService.selectByPrimaryKey(stock.getGoodsId());
            goods.setSoldTimes(goods.getSoldTimes() + o.getNumber());
            goodsService.updateByPrimaryKeySelective(goods);

            categoryHot.setCategoryId(goods.getCategoryId());
            categoryHot.setSoldTimes(o.getNumber());
            categoryHotList.add(categoryHot);
        }
        statisticUtil.categoryHot(categoryHotList);
        StatisticUtil.updateSalesSum(orders.getSellerId(), orders.getDues());
        return new ResponseBean(HttpStatus.OK.value(), "修改成功", null);
    }

    @GetMapping("/getMySold")
    public ResponseBean getMySold(@RequestParam Map<String, Object> map){
        int page = 1, rows = 10;
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());
        PageHelper.startPage(page, rows);
        MasterOrder masterOrder = new MasterOrder();
        masterOrder.setSellerId(Integer.parseInt(map.get("sellerId").toString()));
        List<MasterOrder> masterOrderList = masterOrderService.select(masterOrder);
        List<MasterOrderDto> masterOrderDtoList = new ArrayList<>();
        for (MasterOrder m:masterOrderList
             ) {
            MasterOrderDto masterOrderDto = masterOrderUtil.getMasterOrderDto(m);
            masterOrderDto.setBuyerName(companyInfoService.selectByPrimaryKey(m.getBuyerId()).getCompanyName());
            masterOrderDtoList.add(masterOrderDto);
        }
        PageInfo<MasterOrderDto> selectPage = new PageInfo<>(masterOrderDtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("masterOrderList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    @GetMapping("/getMyBought")
    public ResponseBean getMyBought(@RequestParam Map<String, Object> map){
        int page = 1, rows = 10;
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());
        PageHelper.startPage(page, rows);
        MasterOrder masterOrder = new MasterOrder();
        masterOrder.setBuyerId(Integer.parseInt(map.get("buyerId").toString()));
        List<MasterOrder> masterOrderList = masterOrderService.select(masterOrder);
        List<MasterOrderDto> masterOrderDtoList = new ArrayList<>();
        for (MasterOrder m:masterOrderList
        ) {
            MasterOrderDto masterOrderDto = masterOrderUtil.getMasterOrderDto(m);
            masterOrderDto.setSellerName(companyInfoService.selectByPrimaryKey(m.getSellerId()).getCompanyName());
            masterOrderDtoList.add(masterOrderDto);
        }
        PageInfo<MasterOrderDto> selectPage = new PageInfo<>(masterOrderDtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("masterOrderList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    @GetMapping("/getDetail")
    public ResponseBean getDetail(@RequestParam Integer masterOrderId){
        MasterOrder masterOrder = new MasterOrder();
        masterOrder.setMasterOrderId(masterOrderId);
        MasterOrderDto masterOrderDto = new MasterOrderDto();
        if(masterOrderService.selectCount(masterOrder) != 0) {
            masterOrder = masterOrderService.selectByPrimaryKey(masterOrderId);
            masterOrderDto = masterOrderUtil.getMasterOrderDto(masterOrder);
            masterOrderDto.setBuyerName(companyInfoService.selectByPrimaryKey(masterOrder.getBuyerId()).getCompanyName());
            masterOrderDto.setSellerName(companyInfoService.selectByPrimaryKey(masterOrderDto.getSellerId()).getCompanyName());

            MasterOrderGoods masterOrderGoods = new MasterOrderGoods();
            masterOrderGoods.setMasterOrderId(masterOrderDto.getMasterOrderId());
            List<MasterOrderGoods> masterOrderGoodsList = masterOrderGoodsService.select(masterOrderGoods);

            List<MasterOrderGoodsDto> masterOrderGoodsDtoList = new ArrayList<>();
            for (MasterOrderGoods m : masterOrderGoodsList
            ) {
                MasterOrderGoodsDto masterOrderGoodsDto = new MasterOrderGoodsDto();
                Stock stock = stockService.selectByPrimaryKey(m.getStockId());
                Goods goods = goodsService.selectByPrimaryKey(stock.getGoodsId());
                masterOrderGoodsDto.setGoodsId(stock.getGoodsId());
                masterOrderGoodsDto.setGoodsName(goods.getGoodsName());
                masterOrderGoodsDto.setGoodsImgUrl(JSONObject.parseArray(goods.getGoodsImgUrlList()).getString(0));
                masterOrderGoodsDto.setModelMap(JSONObject.parseObject(stock.getModelMap()));

                masterOrderGoodsDto.setMasterOrderId(m.getMasterOrderId());
                masterOrderGoodsDto.setCompletedNumber(m.getCompletedNumber());
                masterOrderGoodsDto.setFloor(m.getFloor());
                masterOrderGoodsDto.setNumber(m.getNumber());
                masterOrderGoodsDto.setTopLimit(m.getTopLimit());
                masterOrderGoodsDto.setStockId(m.getStockId());
                masterOrderGoodsDto.setPrice(m.getPrice());

                masterOrderGoodsDtoList.add(masterOrderGoodsDto);
            }

            masterOrderDto.setStockList(masterOrderGoodsDtoList);
        }else {
            return new ResponseBean(HttpStatus.OK.value(), "协约不存在", null);
        }
        return new ResponseBean(HttpStatus.OK.value(), "查询成功", masterOrderDto);
    }

    @GetMapping("/childGetMyBought")
    public ResponseBean childGetMyBought(@RequestParam Integer masterOrderId){
        MasterOrder masterOrder = new MasterOrder();
        masterOrder.setMasterOrderId(masterOrderId);
        if(masterOrderService.selectCount(masterOrder) != 0){
            MasterOrderOrders masterOrderOrders = new MasterOrderOrders();
            masterOrderOrders.setMasterOrderId(masterOrderId);
            List<MasterOrderOrders> masterOrderOrdersList = masterOrderOrdersService.select(masterOrderOrders);
            List<OrdersListDto> ordersListDtoList = new ArrayList<>();
            OrdersListDto ordersListDto;
            for (MasterOrderOrders m: masterOrderOrdersList
                 ) {
                ordersListDto = (OrdersListDto) ordersService.selectByPrimaryKey(m.getOrderId());

                ordersListDto.setShopName(shopService.selectByPrimaryKey(ordersListDto.getShopId()).getShopName());

                ordersListDtoList.add(ordersUtil.getOrdersListDtoByOrderId(m.getOrderId(), ordersListDto));
            }
            return new ResponseBean(HttpStatus.OK.value(), "查询成功", ordersListDtoList);
        }
        return new ResponseBean(HttpStatus.OK.value(), "协约不存在", null);
    }

    @GetMapping("/childGetMySold")
    public ResponseBean childGetMySold(@RequestParam Integer masterOrderId){
        MasterOrder masterOrder = new MasterOrder();
        masterOrder.setMasterOrderId(masterOrderId);
        if(masterOrderService.selectCount(masterOrder) != 0){
            MasterOrderOrders masterOrderOrders = new MasterOrderOrders();
            masterOrderOrders.setMasterOrderId(masterOrderId);
            List<MasterOrderOrders> masterOrderOrdersList = masterOrderOrdersService.select(masterOrderOrders);
            List<OrdersListDto> ordersListDtoList = new ArrayList<>();
            OrdersListDto ordersListDto = new OrdersListDto();
            for (MasterOrderOrders m: masterOrderOrdersList
            ) {
                Orders orders =ordersService.selectByPrimaryKey(m.getOrderId());

                ordersListDto.setOrderId(orders.getOrderId());
                ordersListDto.setOrderTime(orders.getOrderTime());
                ordersListDto.setOrderType(orders.getOrderType());
                ordersListDto.setPaymentMode(orders.getPaymentMode());
                ordersListDto.setTransportMode(orders.getTransportMode());
                ordersListDto.setGoodsTotalPrice(orders.getGoodsTotalPrice());
                ordersListDto.setFreight(orders.getFreight());
                ordersListDto.setDues(orders.getDues());
                ordersListDto.setLogisticsNumber(orders.getLogisticsNumber());
                ordersListDto.setGoodsState(orders.getGoodsState());
                ordersListDto.setOrderState(orders.getOrderState());
                ordersListDto.setShopName(companyInfoService.selectByPrimaryKey(orders.getBuyerId()).getCompanyName());

                ordersListDtoList.add(ordersUtil.getOrdersListDtoByOrderId(m.getOrderId(), ordersListDto));
            }
            return new ResponseBean(HttpStatus.OK.value(), "查询成功", ordersListDtoList);
        }
        return new ResponseBean(HttpStatus.OK.value(), "协约不存在", null);
    }
}
